// packageE/goods/goods.js
var app = getApp();
var imageSrcP = require("../../../mybehaviors/imageSrcP");
Component({
  behaviors: [imageSrcP],
  properties: {
    datas: {
      type: null,
    },
    component_id: {
      type: null,
    },
    page_id: {
      type: null,
    },
    index: {
      type: null,
    },
    U_tabcontrol: {
      type: null,
    },
    bottomShowBol: {
      type: null,
    },
    bottomShowBolIndex: {
      type: null,
    },
    isLast: {
      type: null,
    },
    plugin_active: {
      // 会员中心商品加载
      type: null,
    },
    store_alone_temp: {
      // 门店独立判断
      type: null,
    },
    childComponent: {
      type: null,
      value: 'goods'
    },
    // 多项选项卡 start
    childStyle: {
      type: null,
      value: ''
    },
    indTab: {
      type: null
    },
    indexTab: {
      type: null
    },
    infoTab: {
      type: null
    },
    second_list_key: {
      type: null
    },
    all: {
      type: null
    },
    totalAll: {
      type: null
    },
    // 多项选项卡 start
    store_id: {
      type: null
    }
  },
  // 私有数据，可用于模板渲染
  data: {
    integral: "积分",

    showList: false,
    emptyImage: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/image.png",
    clientWidth: "375",
    list: [],
    language: "",
    alreadyHandleArray: [],
    arrIndex: 1,
    market_price_text: '',
    price_text: '',
    goods_cofig: [],
    per_page: 12,

    page: 1,
    total_page: 0,
    isLoadMore: true,
    allLoaded: false, // 全部数据已经加载完成
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      let language = wx.getStorageSync("langIndex");
      this.setData({
        language: language.en,
        thumb_parameter:this.getyz_basic_info()
      });
      let goodsDiy = wx.getStorageSync("yz_basic_info").lang.goods;
      let price_text = goodsDiy && goodsDiy.price ? goodsDiy.price : "现价";
      let market_price_text = goodsDiy && goodsDiy.market_price ? goodsDiy.market_price : "原价";
      let vip_price_txt = goodsDiy && goodsDiy.vip_price ? goodsDiy.vip_price : '会员价';
      let scribing_show = wx.getStorageSync('yz_basic_info').home.mailInfo.scribing_show && wx.getStorageSync('yz_basic_info').home.mailInfo.scribing_show == 1? 1 : 0;
        this.setData({
        price_text: price_text,
        market_price_text: market_price_text,
        vip_price_txt,
        scribing_show
      });

      let value = wx.getStorageSync("integral");
      if (value) {
        this.setData({
          integral: value,
        });
      }
    },
    moved() {},
    detached() {},
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() {},
  // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });
    let basic_info = wx.getStorageSync("yz_basic_info");
    if (basic_info.home.plugin && basic_info.home.plugin.goods_show) {
      this.setData({
        goods_cofig: basic_info.home.plugin.goods_show.goods_group,
        goods_style_set: basic_info.plugin_setting.good_style
      });
    }
    if (this.data.childComponent == 'goods') {
      if (this.data.datas.list.data) {
        this.setData({
          total_page: this.data.datas.list.last_page,
          page: this.data.datas.list.current_page,
          per_page: this.data.datas.list.per_page,
          alreadyHandleArray: this.data.datas.list.data,
          list: this.data.datas.list.data.slice(0, this.data.per_page)
        });
        if (this.data.total_page <= this.data.page) {
          this.setData({
            isLoadMore: false,
            allLoaded: true,
          });
        }

        // this.datas.get_number 限制数量
        if (this.data.datas.get_number && this.data.datas.get_number <= this.data.per_page) {
          this.setData({
            isLoadMore: false,
            allLoaded: true,
            list: this.data.datas.list.data.slice(0, this.data.datas.get_number)
          });
        }
      } else {
        this.setData({
          isLoadMore: false,
          allLoaded: true,
          list: this.data.datas.list,
        });
      }
    }else{
      this.setData({
        total_page: this.data.datas.list.last_page,
        page: this.data.datas.list.current_page,
        per_page: this.data.datas.list.per_page,
        alreadyHandleArray: this.data.datas.list.data,
        list: this.data.datas.list.data
      });
      if (this.data.total_page <= this.data.page) {
        this.setData({
          isLoadMore: false,
          allLoaded: true,
        });
      }
    }


    this.setData({
      showList: true,
    });
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {},
    hide() {},
    resize() {},
  },
  methods: {
    // 多项切换二级分类
    tabTwoContro(infoDatas,index){
      if(this.data.childComponent == 'tab'){
        wx.showLoading({
          title: '加载中',
          icon: 'none'
        });
        this.data.list = [];
        this.setData({
          total_page: infoDatas.last_page,
          page: infoDatas.current_page,
          per_page: infoDatas.per_page,
          alreadyHandleArray: infoDatas.data,
          list: infoDatas.data
        },(cres)=>{
          wx.hideLoading({})
          this.triggerEvent('onReadEnd',{index})
        });
        if (this.data.total_page <= this.data.page) {
          this.setData({
            isLoadMore: false,
            allLoaded: true,
          });
        }
      }
    },
    // 多项选项卡 加载更多
    getKeyInd(allinfo, info) {
      return new Promise((resove, reject) => {
        let ainfo = allinfo[this.data.indexTab];
        ainfo.forEach((element, i) => {
          if (element.tabSelectShow == element.id) {
            resove(element);
          }
        });
      });
    },
    getAllKey(list, totalAll) {
      return new Promise((resove, reject) => {
        let all = totalAll.second_list;
        all.forEach((element, i) => {
          if (element.id == list.id) {
            resove(i);
          }
        });
      });
    },
    async getMoreDataTest(e) {
      let index = this.data.indexTab; // 点击是第几个一级导航
      let ind = this.data.indTab; //点击的是第几个商品组模块
      let info = this.data.infoTab;
      let json = {
        page: this.data.page + 1,
        decorate_id: this.data.page_id,
        component_id: this.data.component_id,
        component_key: "U_moretabcontrol"
      };
      this.setData({page:this.data.page})
      let secondList = await this.getKeyInd(this.data.all, info);
      let secondkey = await this.getAllKey(secondList, this.data.totalAll);
      json.component_info = {
        list_key: index,
        second_list_key: secondkey,
        components_key: ind
      };
      json.component_info = JSON.stringify(json.component_info);
      wx.showLoading({
        title: '加载中',
      });
      if(this.properties.store_id) json.store_id = this.properties.store_id;
      let urlStr = app.getNetAddresss("home-page.get-decorate-page");
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          if (resdata.data.result == 1) {
            let res = resdata.data.data;
            let arr = [];
            arr = this.data.list.concat(res.data);
            this.setData({
              total_page: res.last_page,
              page: res.current_page,
              ['infoTab.remote_data.list.current_page']: res.current_page,
              ['infoTab.remote_data.list.last_page']: res.last_page,
              list: arr
            });
          }
          wx.hideLoading({
            success: (res) => {},
          });
        },
        fail: (res) => {
          wx.hideLoading({
            success: (res) => {},
          });
          console.log(res);
        },
      });
    },
    gotoDetail(e) {
      let id = e.currentTarget.dataset.item.id;
      let option_id = e.currentTarget.dataset.item.category_option_id?`&coid=${e.currentTarget.dataset.item.category_option_id}`:'';
      if (e.currentTarget.dataset.item.plugin_id == 69) {
        wx.navigateTo({
          url: "/packageA/detail_v2/detail_v2?id=" + id + "&name=69" +option_id
        });
      } else if (e.currentTarget.dataset.item.plugin_id == 78) {
        wx.navigateTo({
          url: '/packageA/detail_v2/detail_v2?id=' + id + '&md=1'+option_id
        });
      } else {
        wx.navigateTo({
          url: "/packageA/detail_v2/detail_v2?id=" + id+option_id,
        });
      }
    },
    openShare(e) {
      let item = e.target.dataset.item || e.currentTarget.dataset.item;
      this.triggerEvent("componentGoodShare", item);
    },
    // 获取更多数据
    getMoreData() {
      let that = this;
      if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length >= this.data.per_page) {
        that.setData({
          list: this.data.list.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
          arrIndex: this.data.arrIndex + 1
        });

        if (this.data.datas.get_number && this.data.list.length > this.data.datas.get_number) {
          this.setData({
            isLoadMore: false,
            allLoaded: true,
            list: this.data.list.slice(0, this.data.datas.get_number)
          });
        }
        return;
      }
      this.setData({
        isLoadMore: false,
      });
      if (that.data.page >= that.data.total_page) {
        if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length > 0) {
          that.setData({
            list: this.data.list.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
            arrIndex: this.data.arrIndex + 1
          });
        }

        if (this.data.datas.get_number && this.data.list.length > this.data.datas.get_number) {
          this.setData({
            list: this.data.list.slice(0, this.data.datas.get_number)
          });
        }
      } else {
        that.setData({
          page: that.data.page + 1,
        });
        let urlStr = app.getNetAddresss("home-page.get-decorate-page");
        urlStr += "&page=" + that.data.page;
        urlStr += "&decorate_id=" + that.data.page_id;
        urlStr += "&component_id=" + that.data.component_id;

        if (this.data.U_tabcontrol) {
          urlStr += "&component_key=U_tabcontrol";
          urlStr += "&component_info=" + JSON.stringify({
            list_key: this.data.index
          });
        } else {
          urlStr += "&component_key=U_goods";
        }

        if(this.properties.store_id) urlStr += `&store_id=${this.properties.store_id}`;
        app._getNetWork({
          url: urlStr,
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              let data = that.data.list;
              if (this.data.U_tabcontrol) {
                that.setData({
                  page: res.data[0].remote_data.list.current_page || this.data.page,
                  alreadyHandleArray: this.data.alreadyHandleArray.concat(res.data[0].remote_data.list.data),
                });
                that.setData({
                  list: data.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
                  arrIndex: this.data.arrIndex + 1
                });
                if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length > 0 || that.data.page < that.data.total_page) {
                  that.setData({
                    isLoadMore: true,
                  });
                } else {
                  that.setData({
                    allLoaded: true,
                  });
                }
              } else {
                that.setData({
                  page: res.data.current_page || this.data.page,
                  alreadyHandleArray: this.data.alreadyHandleArray.concat(res.data.data),
                });
                that.setData({
                  list: data.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
                  arrIndex: this.data.arrIndex + 1
                });
                if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length > 0 || that.data.page < that.data.total_page) {
                  // 判断是否最后一页  和 是否数据都加载完
                  that.setData({
                    isLoadMore: true,
                  });
                } else {
                  that.setData({
                    allLoaded: true,
                  });
                }
              }

              if (this.data.datas.get_number && this.data.list.length > this.data.datas.get_number) {
                this.setData({
                  isLoadMore: false,
                  allLoaded: true,
                  list: this.data.list.slice(0, this.data.datas.get_number)
                });
              }
            } else {
              that.setData({
                page: that.data.page - 1,
                isLoadMore: false,
                allLoaded: true,
              });
            }
          },
          fail: function (res) {
            console.log(res);
          },
        });
      }
    },
    // 会员中心用的
    loadMoreMemberData() {
      let that = this;
      that.setData({
        isLoadMore: false,
      });
      if (that.data.page >= that.data.total_page) {
        if (this.data.alreadyHandleArray.slice(12 * this.data.arrIndex).length > 0) {
          that.setData({
            list: this.data.list.concat(this.data.alreadyHandleArray.slice(12 * this.data.arrIndex, 12 * (this.data.arrIndex + 1))),
            arrIndex: this.data.arrIndex + 1,
          });
        }
        return;
      } else {
        that.setData({
          page: that.data.page + 1,
        });
        let urlStr = app.getNetAddresss("member.member.plugin-data");
        if (this.data.store_alone_temp == 1) {
          // 门店独立
          urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.member.nav-data");
        } else if (this.data.store_alone_temp == 2) {
          // 门店独立
          urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.home.nav-data");
        }
        urlStr += "&page=" + that.data.page;
        urlStr += "&code=" + that.data.plugin_active;

        app._getNetWork({
          url: urlStr,
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              let data = that.data.list;
              that.setData({
                page: res.data.data.current_page || this.data.page,
                alreadyHandleArray: this.data.alreadyHandleArray.concat(res.data.data.data),
              });
              that.setData({
                list: data.concat(this.data.alreadyHandleArray.slice(12 * this.data.arrIndex, 12 * (this.data.arrIndex + 1))),
                arrIndex: this.data.arrIndex + 1,
              });
              if (that.data.page < that.data.total_page) {
                that.setData({
                  isLoadMore: true,
                });
              } else {
                that.setData({
                  allLoaded: true,
                });
              }
              that.triggerEvent("setLoadMore", {
                isLoadMore: that.data.isLoadMore,
              });
            } else {
              that.setData({
                page: that.data.page - 1,
                isLoadMore: false,
                allLoaded: true,
              });
            }
          },
          fail: function (res) {
            console.log(res);
          },
        });
      }
    },
  },
  observers: {
    // datas: function (data) {
    //   if (this.data.childComponent == 'tab') {
    //     console.log('ddddddddddd')
    //     this.setData({
    //       total_page: this.data.datas.list.last_page,
    //       page: this.data.datas.list.current_page,
    //       per_page: this.data.datas.list.per_page,
    //       alreadyHandleArray: this.data.datas.list.data,
    //       list: this.data.datas.list.data
    //     });
    //     if (this.data.total_page <= this.data.page) {
    //       this.setData({
    //         isLoadMore: false,
    //         allLoaded: true,
    //       });
    //     }
    //   }
    // },
    // page_id: function (id) {
    //   console.log(id, 'aaa');
    // },
    bottomShowBol: function (flag) {
      console.log(flag);
      if(this.data.childComponent != 'tab'){
        if (this.data.U_tabcontrol) {
          // 选项卡this.isLast判断商品列表是最后一个组件
          if (flag && this.data.isLast && this.data.datas.sort_style.choose_icon != 5 && this.data.isLoadMore) {
            this.getMoreData();
          } else if (this.data.page >= this.data.total_page) {
            if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length > 0) {
              this.setData({
                list: this.data.list.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
                arrIndex: this.data.arrIndex + 1
              });
            }
          }
        } else {
          if (flag && this.data.bottomShowBolIndex == this.data.index && this.data.datas.sort_style.choose_icon != 5 && this.data.isLoadMore) {
            this.getMoreData();
          } else if (this.data.page >= this.data.total_page) {
            if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length > 0) {
              this.setData({
                list: this.data.list.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
                arrIndex: this.data.arrIndex + 1
              });
            }
          }
        }
      }
    },
  },
});